<!-- 人事异动-实习结束 -->
<template>
  <ContentCard>
    <template #header>
      <pageHeaderNew title="实习结束" :showBack="false"></pageHeaderNew>
    </template>
    <ConditionBox :margin-bottom="20">
      <template #left>
        <a-space>
          <div style="display: flex">
            <a-select :options="options" v-model="keyWold" />
            <a-input-search
              @press-enter="search"
              @search="search"
              v-model="keyWoldValue"
              placeholder="请输入"
            />
          </div>
          <a-input-search
            @press-enter="search"
            @search="search"
            v-model="phoneData"
            placeholder="输入手机号码搜索"
          />
          <a-button @click="reset">重置</a-button>
        </a-space>
      </template>
      <template #right>
        <a-button type="primary">办理异动</a-button>
        <a-button type="outline" @click="importVisible = true">导入</a-button>
        <a-button type="outline" @click="exportSettingVisible = true"
          >导出</a-button
        >
        <a-dropdown>
          <a-button type="outline">批量操作</a-button>
          <template #content>
            <a-doption>撤销</a-doption>
            <a-doption>确认</a-doption>
          </template>
        </a-dropdown>
      </template>
    </ConditionBox>
    <TableTurn :tableData="getTableData" :args="args" ref="tableRef">
      <a-table-column :width="80">
        <template #title> 序号 </template>
        <template #cell="{ rowIndex }">
          {{ rowIndex + 1 }}
        </template>
      </a-table-column>
      <TableControlShow
        :selectedHeader="selectedHeader"
        :showCtlCodeArr="showCtlCodeArr"
      />
      <a-table-column :width="150" fixed="right">
        <template #title>
          <a-tooltip content="表头设置">
            <icon-font
              type="icon-filter-def"
              :size="26"
              :style="{
                marginRight: '10px',
                cursor: 'pointer'
              }"
            />
          </a-tooltip>
          <a-tooltip content="表头设置">
            <icon-font
              type="icon-setting-def"
              :size="26"
              :style="{
                cursor: 'pointer'
              }"
              @click="isHeaderSetting"
            />
          </a-tooltip>
        </template>
        <template #cell="{ record }">
          <a-tooltip content="办理异动">
            <icon-font
              type="icon-details-def"
              :size="26"
              :style="{
                cursor: 'pointer',
                marginRight: '10px'
              }"
              @click="goDetail(record)"
            />
          </a-tooltip>
          <a-tooltip content="撤销">
            <icon-font
              type="icon-chexiao"
              :size="26"
              :style="{
                cursor: 'pointer',
                marginRight: '10px'
              }"
              @click="goDetail(record)"
            />
          </a-tooltip>
          <a-tooltip content="更多功能">
            <a-dropdown
              @select="(value: number, e: Event, id: number) => moreItemControl(value, e, record)"
            >
              <icon-font
                type="icon-more-def"
                :size="26"
                :style="{
                  cursor: 'pointer'
                }"
                @click="singleControl(record)"
              />
              <template #content>
                <a-doption :value="1">开具实习证明</a-doption>
                <a-doption :value="2">延长实习期</a-doption>
              </template>
            </a-dropdown>
          </a-tooltip>
        </template>
      </a-table-column>
    </TableTurn>
  </ContentCard>
  <FormHeaderControlSetting
    title="实习结束表头设置"
    v-model:visible="setting"
    :result-list="headerSetting"
    @headerSave="headerSave"
    :orginHeaderList="orginHeaderList.headerListCode"
  >
  </FormHeaderControlSetting>
  <IntershipProof v-model:visible="IntershipProofVisiable" :data="currData">
  </IntershipProof>
</template>
<script setup lang="tsx">
import { Message } from '@arco-design/web-vue';
import { flatTree, dataTreeFilter, downloadExcelFile } from '@/utils/utils';
import clonedeep from 'lodash.clonedeep';
import {
  OnboardingExcel,
  PutPersonnelid,
  EOabcdegiilmnnooprrtx,
  DelOnboarding,
  DelStaff
} from '@/apis/management/personnel/baseSetting/TransactionSetting';
import {
  ChangeHumanInductionState,
  DelHumanList
} from '@/apis/management/personnel/changeManagement/inductionManagement';
import { GetHumanTemplateList } from '@/apis/management/human/baseSetting/humanSetting';
import { ExportHumanRosterList } from '@/apis/management/human/humanRoster';
import {
  PutHeaderSetting,
  GetHeaderSetting,
  PostHeaderSetting
} from '@/apis/management/base/index';
import {
  GetWorkPlaceList,
  GetOrganizationList
} from '@/apis/management/organization/organizationManagement';
import { GetPosition } from '@/apis/management/organization/positionManagement';
import { useRouter } from 'vue-router';
import { GetBusinessModalData } from '@/apis/controltotal/index';
import { GetStaff } from '@/apis/management/personnel/baseSetting/TransactionSetting';
import { PersonnelListParams } from '@/apis/management/personnel/baseSetting/TransactionSetting/type';
import TableTurn, { type paramsType } from '@/components/TableTurn/index.vue';
import { Modal, Button } from '@arco-design/web-vue';
import IntershipProof from '../Evaluation/Components/IntershipProof/index.vue';

// 选择器配置
const args = reactive({
  rowSelection: {
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false
  },
  stripe: true
});
let tableRef = ref();
/* 储存选择的数据 */
const selectedList = computed(() => tableRef.value.selectedList);
const router = useRouter();
let setting = ref(false); // 判断是否点击设置按钮
let headerList = ref(); // 接口获取过来的原始表头数据
let headerSetting = ref<any>([]); // 当前的表头数据
let orginHeaderList = ref([]); // 原始的表头数据

const getTableData = async (params: paramsType) => {
  try {
    const res = await GetStaff({
      ...params,
      typeName: '9',
      [keyWold.value]: keyWoldValue.value,
      mobile: phoneData.value
    });

    res.content.forEach((item: any) => {
      item.ctlValue.forEach((element: any) => {
        item[element.ctlCode] = element.ctlValue;
      });
    });
    return Promise.resolve(res);
  } catch (error: unknown) {
    console.log(error);
  }
};

// 新增表头
const addHeader = async () => {
  //SER_FUNCB6EB0EC09FFA4476B1F61D0E9F5B5FBB
  try {
    const {
      funcCtlInfos: { children }
    } = await GetBusinessModalData({
      funcCode: 'SER_FUNCB6EB0EC09FFA4476B1F61D0E9F5B5FBB'
    });

    let headerListCode: any = [];
    children?.forEach((item1: any) => {
      const { subRelDetail, cnName, subCode } = item1.subDetail;
      subRelDetail?.forEach((item2: any, index2: number) => {
        headerListCode.push(item2.ctlCode);
      });
    });
    await PostHeaderSetting({
      userId: +(localStorage.getItem('userId') as string),
      ownerFuncType: 4,
      headerListCode: headerListCode.join(',')
    });

    init();
  } catch (error: unknown) {
    console.log(error);
  }
};

// 储存要特殊处理的数据
const showInfoData = reactive({
  data: {
    deptList: [], // 组织列表数据
    workPlaceList: [], // 工作地点数据
    positionList: [] // 职位列表数据
  }
});

// 初始化数据
const init = async () => {
  const [
    headerSettingRes,
    businessModalDataRes,
    humanListRes,
    deptListRes,
    workPlaceListRes,
    positionListRes
  ] = await Promise.all([
    // 获取表头
    GetHeaderSetting({
      ownerFuncType: 4,
      userId: +(localStorage.getItem('userId') as string)
    }),
    // 控件数据
    GetBusinessModalData({
      funcCode: 'SER_FUNCB6EB0EC09FFA4476B1F61D0E9F5B5FBB'
    }),
    // 人员列表
    GetHumanTemplateList({
      pageNumber: 0,
      pageSize: -1
    }),
    // 组织列表
    GetOrganizationList({}),
    // 工作地点
    GetWorkPlaceList({
      pageNumber: 0,
      pageSize: -1
    }),
    GetPosition({
      pageNumber: 0,
      pageSize: -1
    })
  ]);

  orginHeaderList.value = headerSettingRes;
  headerSetting.value = [];
  const headerChildren = businessModalDataRes.funcCtlInfos.children;
  headerChildren.forEach((child: any, index: number) => {
    headerSetting.value.push({
      collectionName: child.subDetail.cnName,
      collectionCode: child.subDetail.subCode,
      heads: child.subDetail.subRelDetail.map((subDetail: any) => {
        const isDefault = headerSettingRes.headerListCode.includes(
          subDetail.ctlCode
        );
        return {
          ...subDetail,
          isDefault
        };
      })
    });
  });
  if (headerSettingRes.headerListCode.length < 1) {
    addHeader();
  }
  showInfoData.data.deptList = flatTree(dataTreeFilter(deptListRes));
  showInfoData.data.workPlaceList = workPlaceListRes.content;
  showInfoData.data.positionList = positionListRes.content;
};
init();

// 表格中需要特殊渲染的template
const showCtlCodeArr = [
  'CA8ABCC1480744557B3014C3454465A7E',
  'CED44AC9966904CD1AB546D309903727C',
  'CE009C2E2B542409D815F0D3D54FE0E2B',
  'C2818BAA63AE848AA845DA2E81ECB1843'
];
// 处理特殊渲染的数据
const ShowInfo = (props: any) => {
  const record = props.record;
  const ctlCode = props.ctlCode;
  switch (ctlCode) {
    // 公司
    case 'CA8ABCC1480744557B3014C3454465A7E':
      return (
        <div>
          {
            showInfoData.data.deptList.find(
              (item: any) =>
                item.id == record['CA8ABCC1480744557B3014C3454465A7E']
            )?.name
          }
        </div>
      );
    // 部门
    case 'CED44AC9966904CD1AB546D309903727C':
      return (
        <div>
          {
            showInfoData.data.deptList.find(
              (item: any) =>
                item.id == record['CED44AC9966904CD1AB546D309903727C']
            )?.name
          }
        </div>
      );
    // 工作地点
    case 'CE009C2E2B542409D815F0D3D54FE0E2B':
      return (
        <div>
          {
            showInfoData.data.workPlaceList.find(
              (item: any) =>
                item.id == record['CE009C2E2B542409D815F0D3D54FE0E2B']
            )?.name
          }
        </div>
      );
    // 职位名称
    case 'C2818BAA63AE848AA845DA2E81ECB1843':
      return (
        <div>
          {
            showInfoData.data.positionList.find(
              (item: any) =>
                item.id == record['C2818BAA63AE848AA845DA2E81ECB1843']
            )?.name
          }
        </div>
      );
    default:
      break;
  }
};

// 在表格上显示的表头
const selectedHeader = computed(() => {
  const selectedHeaders: any[] = [];
  headerSetting.value.forEach((headerGroup: any, index: number) => {
    let defaultHeaders = headerGroup.heads.filter(
      (header: any) => header.isDefault === true
    );
    defaultHeaders = defaultHeaders.map((el: any) => {
      const sort = orginHeaderList.value.headerListCode
        .split(',')
        .findIndex((el2: any) => el2 === el.ctlCode);
      return {
        ...el,
        sort
      };
    });
    selectedHeaders.push(...defaultHeaders);
  });

  selectedHeaders.sort((a, b) => a.sort - b.sort);
  // 将姓名移到最前面
  const nameHeaderIndex = selectedHeaders.findIndex(
    (header) => header.ctlCode === 'C62B8DC31189847E0972B5D8F721404B1'
  );
  if (nameHeaderIndex !== -1) {
    selectedHeaders.unshift(...selectedHeaders.splice(nameHeaderIndex, 1));
  }
  return selectedHeaders;
});
// 表头设置返回的自定义事件
const headerSave = async (totalList: any, used: any, unused: any) => {
  try {
    const id = orginHeaderList.value.id;
    const headerListCode = used.map((item: any) => item.ctlCode).join(',');
    await PutHeaderSetting({
      id,
      userId: +localStorage.getItem('userId')!,
      ownerFuncType: 4,
      headerListCode
    });
    headerSetting.value = totalList;
    orginHeaderList.value.headerListCode = headerListCode;
  } catch (error: unknown) {
    console.log(error);
  }
};

const goDetail = (data: any) => {
  router.push({
    name: 'HandleTransaction',
    query: { id: data.id }
  });
};

let singleSelectId = 0; // 储存单个item移动、合并的id
let singleSelectData = {}; // 储存单个item移动、合并的值
// 点击三个小点事件
const singleControl = (record: any) => {
  singleSelectData = record;
  singleSelectId = record.id;
};

// 删除人员
const del = async (id: number | null) => {
  const del2 = async () => {
    if (!id && selectedList.value.length < 1) {
      Message.error('请至少选择一项!');
      return;
    }
    await DelHumanList({
      ids: selectedList.value.length > 0 ? selectedList.value : [id]
    });
    refresh();
  };

  // 如果是按了批量删除的按钮则弹个框出来再删除
  if (!id) {
    Modal.open({
      title: '删除',
      content: <h3> 是否确认删除选中的人员？</h3>,
      onOk: del2
    });
  } else del2();
};

let IntershipProofVisiable = ref(false); // 判断实习开具证明弹出框是否显示
let currId = ref(0), // 储存当前选中行的id
  currData = ref({}); // 储存当前选中行的数据
// 表格中的三个小点按钮的下拉菜单
const moreItemControl = async (key: number, e: Event, record: any) => {
  try {
    let title = e?.target?.innerText;
    let content: any;
    let onOk: (() => void) | undefined;
    let model = ref();
    // let title;
    switch (key) {
      case 1:
        currData.value = record;
        IntershipProofVisiable.value = true;
        break;
      case 2:
        content = <>是否延长实习期？</>;
        break;
      default:
        break;
    }
    // 如果不用弹出框就直接return，用于跳转的发送入职通知
    if (!onOk) return;
    Modal.open({
      title,
      content,
      width: '50%',
      onOk
    });
  } catch (error: unknown) {
    console.log(error);
  }
};

// 模糊查询参数
const options = reactive([
  { label: '姓名', value: 'name' },
  { label: '职位', value: 'positionName' }
]);
// 模糊类型
const keyWold = ref('name');
// 模糊查询值
const keyWoldValue = ref('');

// 是否显示表头
const isHeaderSetting = async () => {
  try {
    setting.value = !setting.value;
  } catch (error: unknown) {
    console.log(error);
  }
};
const phoneData = ref('');
const search = () => {
  refresh();
};

// 重置数据
const reset = () => {
  keyWold.value = 'name';
  keyWoldValue.value = '';
  phoneData.value = '';
  refresh();
};

// 刷新列表
const refresh = (page?: any) => {
  tableRef.value.loadData(page);
};

let rcolor = 'red';
</script>
<style lang="less" scoped>
.wrap {
  padding: 10px 20px;

  // 弄出一个小的圆形
}
</style>
